import urllib.request
import urllib.parse
import json

baseUrl = 'https://translation.googleapis.com/language/translate/v2?'
key = "AIzaSyD_5mrc9mF82dVUVeg2Obv8hnN-IJz6Kco"


def translate(text_list, l_from, l_to, model):
    """从url中获取数据"""
    header = {
        'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }  # 头部信息
    url = baseUrl + 'key=' + key
    if l_to:
        url = url + '&target=' + l_to
    if l_from:
        url = url + '&source=' + l_from
    if model:
        url = url + '&model=' + model
    if text_list is None:
        raise Exception('text_list %s' % '不能为空')
    if type(text_list) != list:
        raise Exception('text_list %s' % '格式需要为list')
    for v in text_list:
        url = url + '&q=' + urllib.parse.quote_plus(v)
    request = urllib.request.Request(url=url, headers=header)  # 请求处理
    b64_text = json.loads(urllib.request.urlopen(request).read())  # 读取结果
    result = []
    for v in b64_text['data']['translations']:
        result.append(v['translatedText'])
    return result


if __name__ == '__main__':
    text_list = ['你好', '']
    text = translate(text_list=text_list, l_from=None, model=None, l_to='en')

    print(text)
